package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author solang
 * @date 2022-12-26 16:05
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {
    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;
    /**
     * 判断删除id分类是否关联菜品或套餐,才能删除
     * @param id
     */
    @Override
    public void remove(Long id) {
        LambdaQueryWrapper<Dish> dishQueryWrapper = new LambdaQueryWrapper<>();
        //添加查询条件,查询是否关联菜品
        dishQueryWrapper.eq(Dish::getCategoryId ,id);
        int dishCount = dishService.count(dishQueryWrapper);
        //查询是否关联菜品,如true,抛出异常
        if(dishCount>0){
            //已关联菜品,抛出异常
            throw  new CustomException("当前分类已关联菜品,不可删除");
        }
        //========================================================================
        //添加查询条件,查询是否关联套餐
        LambdaQueryWrapper<Setmeal> setmealQueryWrapper = new LambdaQueryWrapper<>();
        setmealQueryWrapper.eq(Setmeal::getCategoryId,id);
//        int SetmealCount = setmealService.count();
        //查询是否关联套餐,如true,抛出异常
        if(setmealService.count(setmealQueryWrapper)>0){
            //已关联套餐,抛出异常
            throw  new CustomException("当前分类已关联套餐,不可删除");
        }
        //没有管理菜品或套餐,删除
        super.removeById(id);

    }
}
